/*
 * Copyright 2010 Mark Eschbach.
 *
 * $HeadURL$
 * $Id$
 */
package com.meschbach.cise.resource.jar;

import com.meschbach.cise.iterator.MIterator;
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

/**
 *
 * @author "Mark Eschbach" &lt;meschbach@gmail.com&gt;
 */
public class JarEntryIterator implements MIterator<JarEntry, IOException> {

    JarInputStream input;
    JarEntry entry;

    public JarEntryIterator(JarInputStream input) {
        this.input = input;
        entry = null;
    }

    public boolean hasNext() throws IOException {
        /*
         * Have we already found the entry?
         */
        if (entry != null) {
            return true;
        }
        /*
         * Nope, grab the next entry
         */
        entry = input.getNextJarEntry();
        return entry != null;
    }

    public JarEntry next() throws IOException {
        /*
         * Ensure we have an additional element
         */
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        /*
         *
         */
        JarEntry result = entry;
        entry = null;
        return result;
    }

    public void close() {
        try {
            input.close();
        } catch (Throwable t) {
            throw new IllegalStateException("Unable to close source stream", t);
        }
    }
}
